package com.bshinfo.web.service.serviceImpl.adminManage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.bshinfo.web.base.model.Page;
import com.bshinfo.web.base.util.ConstantUtil;
import com.bshinfo.web.base.util.PaginationUtil;
import com.bshinfo.web.dao.adminManage.AdminManageMapper;
import com.bshinfo.web.model.dataTableUtil.DataTableModel;
import com.bshinfo.web.service.serviceI.adminManage.AdminManageServiceI;

/**
 * MainMenu业务逻辑层实现类 <br/>
 * 
 * 功能描述: 对MainMenu的各种业务处理 <BR/>
 * 
 * @author 	[zhangxinhua]
 * 
 * @see 	[MainServiceImpl]
 * 
 * @since 	[JDK 1.7] 
 * 
 * @version [1.0]
 * 
 * @Date    [2017-2-17 16:20:25]
 */
@Service
public class AdminManageServiceImpl implements AdminManageServiceI 
{

	@Resource
	AdminManageMapper adminManageMapper;
	
	@Override
	public DataTableModel selectAdminInfo(Map<String, String> dataTableMap,String nowUserId) 
	{
		Map<String,Object> paramMap = new HashMap<String,Object>();
		DataTableModel tableModel=new DataTableModel();
		List<List<Object>> dataList=new ArrayList<>();
		String sEcho = dataTableMap.get("sEcho");
	    int start = Integer.parseInt(dataTableMap.get("iDisplayStart"));
	    int length = Integer.parseInt(dataTableMap.get("iDisplayLength"));
	    int currentPage = start/length + 1;
	    paramMap.put("user_name",dataTableMap.get("user_name"));
	    paramMap.put("create_user_id",nowUserId);
	    paramMap.put("real_name",dataTableMap.get("real_name"));
	    paramMap.put("create_user_name",dataTableMap.get("create_user_name"));
	    paramMap.put("site_id",dataTableMap.get("site_id"));
	    paramMap.put("fromTime",dataTableMap.get("fromTime"));
	    paramMap.put("toTime",dataTableMap.get("toTime"));
	    Page<Map<String, Object>> page = PaginationUtil.setPageInfoStart(paramMap,currentPage,length);
	    
	    List<Map<String,Object>> userList = adminManageMapper.selectAdminInfo(page);
	    /*for (int i=0;i<userList.size();i++) 
	    {
	    	Map<String, Object> map = userList.get(i);
	    	Map<String, Object> siteMap = adminManageMapper.getSitesByUserId(map);
	    	map.put("site_name", siteMap.get("site_name"));
	    	Map<String, Object> roleMap = adminManageMapper.getRolesByUserId(map);
	    	map.put("role_name", roleMap.get("role_name"));
		}*/
		for(Map<String, Object> map : userList)
		{
			//行
			List<Object> list=new ArrayList<Object>();
			list.add(map.get("id"));
			list.add("");
			list.add(map.get("user_name"));
			list.add(map.get("real_name")==null?"":map.get("real_name"));
			list.add(map.get("create_user_id"));
			list.add(map.get("role_name"));
			list.add(map.get("site_name"));
			list.add(map.get("time"));
			dataList.add(list);
		}
		
		//获取数量
		List<Map<String,Object>> list = adminManageMapper.getCount(paramMap);
		List<Object> countList=new ArrayList<Object>();
		for (Map<String, Object> map : list) 
		{
			if(!countList.contains(map.get("id")))
			{
				countList.add(map.get("id"));
			}
		}
		tableModel.setiTotalDisplayRecords(list.size());
		tableModel.setiTotalRecords(list.size());
		tableModel.setsEcho(Integer.valueOf(sEcho));
		tableModel.setAaData(dataList);
		return tableModel;
	}
	
	@Override
	public List<Map<String, Object>> getSelectList(String userId) 
	{
		Map<String, Object> paramMap=new HashMap<String,Object>();
		paramMap.put("user_id", userId);
		//Page<Map<String, Object>> page = PaginationUtil.setPageInfoStart(paramMap,1,1);
        
        //List<Map<String, Object>> resList = this.adminManageMapper.roleList(page);
        //是否是超管
        if(userId.equals(ConstantUtil.ADMIN_ID))
        {
            return adminManageMapper.getAllSite();
        }
        else 
        {
            return adminManageMapper.getSiteByUserId(paramMap);
        }
	}

	@Override
	public DataTableModel roleList(Map<String, String> dataTableMap,String nowUserId) 
	{
		Map<String,Object> paramMap = new HashMap<String,Object>();
		
		DataTableModel dataTableModel = new DataTableModel();
		
		List<List<Object>> data=new ArrayList<List<Object>>();
		
		String sEcho = dataTableMap.get("sEcho");
		int start = Integer.parseInt(dataTableMap.get("iDisplayStart"));
		int length = Integer.parseInt(dataTableMap.get("iDisplayLength"));
		int currentPage = start/length + 1;
		
		paramMap.put("roleName", dataTableMap.get("sname").trim());
		paramMap.put("user_id", nowUserId);
		Page<Map<String, Object>> page = PaginationUtil.setPageInfoStart(paramMap,currentPage,length);
		
		List<Map<String, Object>> resList = this.adminManageMapper.roleList(page);
		Integer count = adminManageMapper.findRoleCount(paramMap);
		//是否是超管
		if(nowUserId.equals(ConstantUtil.ADMIN_ID))
		{
		    resList.clear();
            resList=adminManageMapper.allRoleList(page);
            count=adminManageMapper.findAddRoleCount(paramMap);
		}
		List<Map<String, Object>> newRoleList=new ArrayList<Map<String, Object>>();
		List<Object> idsList=new ArrayList<Object>();
		for (Map<String, Object> map : resList) 
		{
			if(!idsList.contains(map.get("id")))
			{
				idsList.add(map.get("id"));
				newRoleList.add(map);
			}
		}
		
		//if（“dfs”==ConstantUtil.ADMIN_ID）
		for (Map<String, Object> map : newRoleList) 
		{
			List<Object> rowList = new ArrayList<Object>();
			rowList.add(map.get("id"));
			rowList.add("");
			rowList.add(map.get("role_name"));
			rowList.add("");
			rowList.add(map.get("create_time"));
			data.add(rowList);
		}
		dataTableModel.setiTotalDisplayRecords(count);
		dataTableModel.setiTotalRecords(count);
		dataTableModel.setsEcho(Integer.valueOf(sEcho));
		dataTableModel.setAaData(data);
		
		return dataTableModel;
	}

	@Override
	public Integer addUserRoleBatch(String userids,String roleids,String nowUserId) 
	{
		List<Map<String, Object>> userRoleList=new ArrayList<Map<String,Object>>();
		JSONObject userIds = JSONObject.fromObject(userids);
		if(userIds!=null)
		{
			Iterator<?> iterator = userIds.keys();
			while(iterator.hasNext())
			{
				String key = (String) iterator.next();
	            String value = userIds.getString(key);
	            //遍历role
	            JSONObject roleIds = JSONObject.fromObject(roleids);
	            if(roleIds!=null)
	            {
	            	Iterator<?> roleIterator = roleIds.keys();
	            	while(roleIterator.hasNext()){
	            		String roleKey = (String) roleIterator.next();
	    	            String roleValue = roleIds.getString(roleKey);
	    	            if(value!=null&&!"".equals(value)&&roleValue!=null&&!"".equals(roleValue))
	    	            {
	    	            	Map<String, Object> userRoleMap=new HashMap<String, Object>();
	    	            	userRoleMap.put("user_id", value);
		    	            userRoleMap.put("role_id", roleValue);
		    	            userRoleMap.put("create_user_id", nowUserId);
		    	            if(adminManageMapper.isExiteByUserAndRole(userRoleMap)==0)
		    	            {
		    	            	userRoleList.add(userRoleMap);
		    	            }
	    	            }
	            	}
	            }
			}
		}
		if(userRoleList.size()>0)
		{
			return adminManageMapper.addUserRoleBatch(userRoleList);
		}
		else
		{
			return 1;
		}
	}

	@Override
	public Integer addUserSiteBatch(String userids,String siteids,String nowUserId) 
	{
		List<Map<String, Object>> userSiteList=new ArrayList<Map<String,Object>>();
		JSONObject userIds = JSONObject.fromObject(userids);
		if(userIds!=null)
		{
			Iterator<?> iterator = userIds.keys();
			while(iterator.hasNext())
			{
				String key = (String) iterator.next();
	            String value = userIds.getString(key);
	            //遍历site 去掉两边括号
	            String newSiteIds=siteids.substring(1, siteids.length()-1);
	            String[] siteIds = newSiteIds.split(",");
	            for (String siteId : siteIds) 
	            {
	            	if(value!=null&&!"".equals(value)&&siteId!=null&&!"".equals(siteId))
	            	{
	            		Map<String, Object> userSiteMap=new HashMap<String, Object>();
		            	userSiteMap.put("user_id", value);
		            	userSiteMap.put("site_id", siteId.substring(1, siteId.length()-1));
		            	userSiteMap.put("create_user_id", nowUserId);
		            	if(adminManageMapper.isExiteByUserAndSite(userSiteMap)==0){
		            		userSiteList.add(userSiteMap);
		            	}
	            	}
				}
			}
		}
		if(userSiteList.size()>0)
		{
			return adminManageMapper.addUserSiteBatch(userSiteList);
		}
		else
		{
			return 1;
		}
	}

	@Override
	public List<Map<String, Object>> getRoleByUserid(Map<String, Object> paramMap) 
	{
		return adminManageMapper.getRoleByUserid(paramMap);
	}

	@Override
	public Integer updateUserRoleBatch(String userids, String roleids,String nowUserId) 
	{
		List<Map<String, Object>> userRoleList=new ArrayList<Map<String,Object>>();
		//先将用户的原有的角色删除
		JSONObject userIds = JSONObject.fromObject(userids);
		if(userIds!=null)
		{
			Iterator<?> iterator = userIds.keys();
			while(iterator.hasNext())
			{
				Map<String, Object> paramMap=new HashMap<String,Object>();
				String key = (String) iterator.next();
	            String value = userIds.getString(key);
	            paramMap.put("user_id", value);
	            userRoleList.add(paramMap);
			}
		}
		if("{}".equals(roleids))
		{
		    return 1;
		}
		else
		{
		    adminManageMapper.deleteUserRoleByUserIds(userRoleList);
            return addUserRoleBatch(userids, roleids,nowUserId);
        }
	}

	@Override
	public Integer updateUserSiteBatch(String userids, String siteids,String nowUserId) 
	{
		List<Map<String, Object>> userSiteList=new ArrayList<Map<String,Object>>();
		//先将用户的原有的站点删除
		JSONObject userIds = JSONObject.fromObject(userids);
		if(userIds!=null)
		{
			Iterator<?> iterator = userIds.keys();
			while(iterator.hasNext())
			{
				Map<String, Object> paramMap=new HashMap<String,Object>();
				String key = (String) iterator.next();
	            String value = userIds.getString(key);
	            paramMap.put("user_id", value);
	            userSiteList.add(paramMap);
			}
		}
		adminManageMapper.deleteUserSiteByUserIds(userSiteList);
		return addUserSiteBatch(userids, siteids,nowUserId);
	}

	@Override
	public List<Map<String, Object>> getManageUsersByUserid(String userId) 
	{
		List<Map<String, Object>> userList=new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> newUserList=new ArrayList<Map<String, Object>>();
		List<Object> idsList=new ArrayList<Object>();
		Map<String, Object> paramMap=new HashMap<String,Object>();
		paramMap.put("create_user_id", userId);
		userList = adminManageMapper.getManageUsersByUserConf(paramMap);
		//处理重复数据
		for (Map<String, Object> map : userList) 
		{
			if(!idsList.contains(map.get("id")))
			{
				idsList.add(map.get("id"));
				newUserList.add(map);
			}
		}
		return newUserList;
	}

	@Override
	public boolean deleteUserBatch(String userids,String nowUserId) 
	{
		boolean flag=true;
		JSONObject userIds = JSONObject.fromObject(userids);
		if(userIds!=null)
		{
			Iterator<?> iterator = userIds.keys();
			while(iterator.hasNext())
			{
				String key = (String) iterator.next();
	            String value = userIds.getString(key);
	            if(!"".equals(value))
	            {
	                Map<String, Object> paramMap=new HashMap<String,Object>();
	                paramMap.put("newUserId", nowUserId);
	                paramMap.put("oldUserId", value);
	                adminManageMapper.updateCreateUserId(paramMap);
	                adminManageMapper.updateSiteCreateUserId(paramMap);
	                Integer role = adminManageMapper.deleteUser(value);
	                Integer site = adminManageMapper.deleteSiteUser(value);
	                if(role==0||site==0)
	                {
	                    flag=false;
	                }
	            }
			}
		}
		return flag;
	}

	@Override
	public List<Map<String, Object>> getGroupTree(String nowUserId) 
	{
		Map<String, Object> paramMap=new HashMap<String,Object>();
		paramMap.put("user_id", nowUserId);
		if(nowUserId.equals(ConstantUtil.ADMIN_ID))
		{
		    return adminManageMapper.adminGetTree();
		}
		else
		{
		    return adminManageMapper.getTree(paramMap);
        }
		
	}

    @Override
    public List<Map<String, Object>> roleSourceAndMenu(String roleId)
    {
        List<Map<String, Object>> resultList=new ArrayList<Map<String,Object>>();
        Map<String, Object> paramMap=new HashMap<String,Object>();
        paramMap.put("role_id", roleId);
        if(roleId.equals(ConstantUtil.ADMIN_ROLE_ID))
        {
            List<Map<String,Object>> source = adminManageMapper.getAllSource();
            resultList.addAll(source);
            List<Map<String,Object>> menu = adminManageMapper.getAllMenu();
            resultList.addAll(menu);
        }
        else
        {
            List<Map<String,Object>> sourceAndMenu = adminManageMapper.getSourceOrSourceMenu(paramMap);
            List<Map<String,Object>> source = adminManageMapper.getSource(sourceAndMenu);
            resultList.addAll(source);
            List<Map<String,Object>> menu = adminManageMapper.getMenu(sourceAndMenu);
            resultList.addAll(menu);
        }
        /*for (Map<String, Object> map : sourceAndMenu)
        {
            if(!"3".equals(map.get("resource_type").toString()))
            {
               //资源 
                List<Map<String,Object>> source = adminManageMapper.getSource(sourceAndMenu);
                resultList.addAll(source);
            }
            else if("3".equals(map.get("resource_type").toString()))
            {
               //资源 菜单
                List<Map<String,Object>> menu = adminManageMapper.getMenu(sourceAndMenu);
                resultList.addAll(menu);
            }
        }*/
        return resultList;
    }

    @Override
    public DataTableModel getSite(Map<String, String> dataTableMap,String nowUserId)
    {
        List<Map<String, Object>> resultList=new ArrayList<Map<String,Object>>();
        int count=0;
        List<List<Object>> data=new ArrayList<List<Object>>();
        DataTableModel tableModel=new DataTableModel();
        Map<String, Object> paramMap=new HashMap<String,Object>();
        paramMap.put("user_id", nowUserId);
        paramMap.put("site_name",dataTableMap.get("site_name").toString().trim());
        paramMap.put("site_type",dataTableMap.get("site_type"));
        /*paramMap.put("end",dataTableMap.get("end")+ ("".equals(dataTableMap.get("end")) || dataTableMap.get("end") == null ? "" : " 23:59:59"));
        paramMap.put("site",dataTableMap.get("site"));
        paramMap.put("realName",dataTableMap.get("realName"));
        paramMap.put("status",dataTableMap.get("status"));*/
        //分页处理
        String sEcho = dataTableMap.get("sEcho");
        int start = Integer.parseInt(dataTableMap.get("iDisplayStart"));
        int length = Integer.parseInt(dataTableMap.get("iDisplayLength"));
        int currentPage = start/length + 1;
        //分页结束
        Page<Map<String, Object>> page = PaginationUtil.setPageInfoStart(paramMap,currentPage,length);
        if(nowUserId.equals(ConstantUtil.ADMIN_ID))
        {
            //管理员 获取到所有的站点树
            resultList=adminManageMapper.getAllTableSite(page);
            count=adminManageMapper.getAllTableSiteCount(paramMap);
        }
        else
        {
            //非超级管理员  获取该用户管辖的站点数据
            resultList=adminManageMapper.getTableSite(page);
            count=adminManageMapper.getTableSiteCount(paramMap);
        }
        for (Map<String, Object> map : resultList)
        {
            List<Object> rowList = new ArrayList<Object>();
            rowList.add(map.get("id"));
            rowList.add("");
            rowList.add(map.get("site_name"));
            rowList.add(map.get("site_type"));
            data.add(rowList);
        }
        tableModel.setiTotalDisplayRecords(count);
        tableModel.setiTotalRecords(count);
        tableModel.setsEcho(Integer.valueOf(sEcho));
        tableModel.setAaData(data);
        return tableModel;
    }

}
